﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;

namespace Tsanie.Mp3Tag {
    public class TagUtil {

        public static TagBase ReadTag(string filename) {
            TagBase result = null;
            FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            byte[] buffer = new byte[4];
            if (fs.Read(buffer, 0, 4) == 4) {
                if (buffer[0] == 0x49 && // byte 'I'
                    buffer[1] == 0x44 && // byte 'D'
                    buffer[2] == 0x33 && // byte '3'
                    buffer[3] == 0x03)   // byte '\3' Version
                {
                    result = new ID3v2(fs);
                } else {
                    fs.Seek(fs.Length - 124, SeekOrigin.Current);
                    fs.Read(buffer, 0, 3);
                    if (buffer[0] == 0x54 && // byte 'T'
                        buffer[1] == 0x41 && // byte 'A'
                        buffer[2] == 0x47)   // byte 'G'
                    {
                        result = new ID3v1(fs);
                    }
                }
            }
            fs.Close();
            return result;
        }

        public static string GetGenre(string genre) {
            int index;
            if (int.TryParse(genre.Trim(new char[] { ' ', '(', ')' }), out index))
                return Definition.Genres[index];
            return null;
        }

        public static Image GetImage(byte[] buffer) {
            if (buffer == null)
                return null;
            int index = 1;
            StringBuilder builder = new StringBuilder(0x10);
            for (; index < buffer.Length; index++) {
                if (buffer[index] == 0)
                    break;  // MIME-end
                builder.Append((char)buffer[index]);
            }
            switch (builder.ToString()) {
                case "image/jpg":
                case "image/jpeg":
                case "image/png":
                    break;
                default:
                    return null;
            }
            byte type = buffer[++index];
            for (; index < buffer.Length; index++) {
                if (buffer[index] == 0)
                    break;  // Description-end
            }
            index++;
            if (index > buffer.Length - 1)
                return null;
            MemoryStream ms = new MemoryStream(buffer, index, buffer.Length - index, false);
            Image rtn = System.Drawing.Image.FromStream(ms);
            ms.Close();
            return rtn;
        }

    }
}
